package cn.com.qtgl.sso.oidc.comp.interceptor;

import cn.com.qtgl.oauth2.TokenManager;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.melonlib.apis.support.annos.AppendTenant;
import cn.melonlib.apis.support.annos.IgnoreAppend;
import cn.melonlib.cores.identification.comp.messenger.MessengerUtils;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

import static cn.melonlib.cores.aop.comp.web.WebInfo.hasParamsUrlRegex;

@Component
public class AppendTenantInterceptor implements MethodInterceptor {

    @Resource
    @Lazy
    private TokenManager tokenManager;
    @Resource
    @Lazy
    private MessengerUtils messengerUtils;

    @Nullable
    @Override
    public Object invoke(@NotNull MethodInvocation invocation) throws Throwable {
        if(CharSequence.class.isAssignableFrom(invocation.getMethod().getReturnType())){
            Class cls=AopUtils.getTargetClass(invocation.getThis());
            IgnoreAppend ignoreAppend=AnnotationUtils.findAnnotation(invocation.getMethod(), IgnoreAppend.class);
            if(ignoreAppend==null&&invocation.getMethod().getName().startsWith("get")){
                Field field= ReflectUtil.getField(cls, StrUtil.removePreAndLowerFirst(invocation.getMethod().getName(),"get"));
                if(field!=null) {
                    ignoreAppend = AnnotationUtils.findAnnotation(field, IgnoreAppend.class);
                }
            }
            if(ignoreAppend!=null){
                return invocation.proceed();
            }
            CharSequence result= (CharSequence) invocation.proceed();
            String tenant=messengerUtils.getTenant();
            if(StringUtils.isBlank(tenant)){
                return result;
            }
            if(hasParamsUrlRegex.matcher(result).matches()){
                return result+"&domain="+tenant;
            }else{
                return result+"?domain="+tenant;
            }
        }else{
            return invocation.proceed();
        }
    }
}
